package product

import (
	"context"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ProductAddLogic) ProductAdd(req *types.ProductAddRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)
	//1.客户是否存在
	_, err = l.svcCtx.ClientModel.FindOne(l.ctx, req.ClientId)
	switch err {
	case nil: //不处理
	case model.ErrNotFound: //不存在
		resp.Code = http.StatusBadRequest
		resp.Msg = "客户不存在"
		return resp, nil
	default: //其他错误
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.产品是否存在
	_, err = l.svcCtx.ProductModel.FindOneByModel(l.ctx, req.Model)
	if err != model.ErrNotFound { //内部错误、产品已存在
		resp.Code = http.StatusBadRequest
		resp.Msg = "产品型号已存在"
		return
	}

	//3.录入产品信息
	_, err = l.svcCtx.ProductModel.Insert(l.ctx, &model.Product{
		ClientId: req.ClientId,
		Model:    req.Model,
		Name:     req.Name,
		Specs:    req.Specs,
	})
	if err != nil {
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务器内部错误"
		return
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return
}
